﻿@using Frogsoft.Permission.Dtos
@implements IDialogContentComponent<AppUserDto>
@rendermode InteractiveServer
@inject Frogsoft.Permission.UserService UserService
@attribute [Authorize(Policy = "system_permission_user")]

<FluentStack Wrap="true">
    @if (roleInfo != null)
    {
        @foreach (var role in roleInfo.allItems)
        {
            <div class="role-item">
                <FluentCheckbox @bind-Value="role.Checked"
                                Label="@role.title" />
            </div>
        }
    }
</FluentStack>

<FluentDialogFooter>
    <FluentButton Appearance="Appearance.Accent" @onclick="SaveRoles">保存</FluentButton>
    <FluentButton @onclick="CloseDialog">取消</FluentButton>
</FluentDialogFooter>
    

@code {
    [Parameter]
    public AppUserDto Content { get; set; } = default!;

    [CascadingParameter]
    public FluentDialog? Dialog { get; set; }

    private AppUserRoleDto? roleInfo;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadUserRoles();
    }

    private async Task LoadUserRoles()
    {
        // 获取用户当前的角色信息
        roleInfo = await UserService.GetUserRoleAsync(Content.UserName);
        
        // 根据用户已分配的角色设置复选框状态
        if (roleInfo != null && roleInfo.grantItems != null)
        {
            foreach (var role in roleInfo.allItems)
            {
                role.Checked = roleInfo.grantItems.Contains(role.value);
            }
        }
    }

    private async Task SaveRoles()
    {
        try
        {
            if (roleInfo != null)
            {
                // 获取所有被选中的角色
                var selectedRoles = roleInfo.allItems.Where(r => r.Checked).ToList();
                
                // 更新用户角色
                UserService.UpdateUserRole(Content.UserName, selectedRoles);
                
                // 关闭对话框并返回成功结果
                await Dialog?.CloseAsync();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error updating user roles: {ex.Message}");
            // 这里可以添加错误处理，比如显示错误消息
        }
    }

    private Task CloseDialog()
    {
        return Dialog?.CloseAsync();
    }
}
